package com.example.job.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

import com.example.job.Model.JobModel;
import com.example.job.R;
import com.example.job.Repository.JobDataRepository;
import com.example.job.db.jobdb;
import com.example.job.entity.Job;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class indexFragment extends Fragment {

    private PieChart pieChart;
    private BarChart barChart;
    private ArrayList<String> labels; // 声明 labels 为类成员变量

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_index, container, false);

        pieChart = view.findViewById(R.id.pieChart);
        barChart = view.findViewById(R.id.barChart);
        setupPieChart();
        setupBarChart();

        try {
            InputStream inputStream = getJsonInputStream();
            List<Job> jobs = jobdb.parseJson(inputStream);
            insertJobsToDatabase(jobs);
            System.out.println("Job data inserted successfully");
            loadChartData();
            loadBarChartData();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("indexFragment", "Failed to insert data into jobs table", e);
        }

        return view;
    }

    private InputStream getJsonInputStream() {
        return getResources().openRawResource(R.raw.jobdata);
    }

    // 初始化数据
    private void insertJobsToDatabase(List<Job> jobs) {
        Context context = getContext();
        if (context != null) {
            jobdb.insertJobs(context, jobs);
        }
    }

    // 清空数据库
    private void clearJobsTable() {
        Context context = getContext();
        if (context != null) {
            jobdb dbHelper = new jobdb(context);
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            db.delete("jobs", null, null);
            db.close();
        }
    }

    // 设置 PieChart 属性
    private void setupPieChart() {
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setExtraOffsets(5, 10, 5, 5);
        pieChart.setDragDecelerationFrictionCoef(0.95f);
        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(android.graphics.Color.TRANSPARENT);
        pieChart.setTransparentCircleColor(android.graphics.Color.WHITE);
        pieChart.setTransparentCircleAlpha(110);
        pieChart.setHoleRadius(58f);
        pieChart.setTransparentCircleRadius(61f);
        pieChart.setDrawCenterText(true);
        pieChart.setRotationAngle(0);
        pieChart.setRotationEnabled(true);
        pieChart.setHighlightPerTapEnabled(true);
    }

    // 设置 BarChart 属性
    private void setupBarChart() {
        barChart.getDescription().setEnabled(false);
        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(true);
        barChart.setMaxVisibleValueCount(60);
        barChart.setPinchZoom(false);
        barChart.setDrawGridBackground(false);

        // 设置 X 轴显示在底部
        barChart.getXAxis().setPosition(com.github.mikephil.charting.components.XAxis.XAxisPosition.BOTTOM);

        // 设置 X 轴标签字体大小
        barChart.getXAxis().setTextSize(10f); // 调整字体大小
    }

    // 加载图表数据
    private void loadChartData() {
        Context context = getContext();
        if (context != null) {
            JobDataRepository repository = new JobDataRepository(context);
            List<JobModel> jobs = repository.getJobs();

            Map<String, Integer> typeCounts = new HashMap<>();
            for (JobModel job : jobs) {
                String type = job.getType();
                typeCounts.put(type, typeCounts.getOrDefault(type, 0) + 1);
            }

            ArrayList<PieEntry> entries = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : typeCounts.entrySet()) {
                entries.add(new PieEntry(entry.getValue(), entry.getKey()));
            }

            PieDataSet dataSet = new PieDataSet(entries, "职位类型数量");
            dataSet.setSliceSpace(3f);
            dataSet.setSelectionShift(5f);
            dataSet.setColors(ColorTemplate.MATERIAL_COLORS);

            PieData data = new PieData(dataSet);
            data.setValueTextSize(10f);
            data.setValueTextColor(android.graphics.Color.WHITE);

            pieChart.setData(data);
            pieChart.invalidate(); // 刷新图表
        }
    }

    // 加载柱状图数据
    private void loadBarChartData() {
        Context context = getContext();
        if (context != null) {
            JobDataRepository repository = new JobDataRepository(context);
            List<JobModel> jobs = repository.getJobs();

            Map<String, Map<String, Integer>> cityTypeCounts = new HashMap<>();
            for (JobModel job : jobs) {
                String city = job.getCity();
                String type = job.getType();
                cityTypeCounts.computeIfAbsent(city, k -> new HashMap<>()).merge(type, 1, Integer::sum);
            }

            ArrayList<BarEntry> entries = new ArrayList<>();
            labels = new ArrayList<>(); // 初始化 labels

            int index = 0;
            for (Map.Entry<String, Map<String, Integer>> cityEntry : cityTypeCounts.entrySet()) {
                String city = cityEntry.getKey();
                Map<String, Integer> typeCounts = cityEntry.getValue();
                float sum = typeCounts.values().stream().mapToInt(Integer::intValue).sum();
                entries.add(new BarEntry(index, sum));
                labels.add(city);
                index++;
            }

            BarDataSet dataSet = new BarDataSet(entries, "城市与职业类型关系");
            dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
            dataSet.setValueTextColor(android.graphics.Color.BLACK);
            dataSet.setValueTextSize(6f);

            BarData barData = new BarData(dataSet);
            barData.setBarWidth(0.8f); // 设置柱子宽度

            barChart.setData(barData);
            barChart.getXAxis().setValueFormatter(new ValueFormatter() {
                @Override
                public String getFormattedValue(float value) {
                    return formatLabel(value);
                }
            });
            barChart.invalidate(); // 刷新图表
        }
    }

    // 格式化 X 轴标签
    private String formatLabel(float value) {
        return labels.get((int) Math.floor(value)); // 移除多余的类型转换
    }
}
